import hashlib
import json

from flask import Flask, request
from sqlalchemy import create_engine, Integer, Column, String, Table, or_
from sqlalchemy.orm import sessionmaker, scoped_session, declarative_base

app = Flask(__name__)

# 创建一个引擎，目的是连接到我们的数据库上
engine = create_engine('mysql+pymysql://root:123456@127.0.0.1:3306/mumushouji',echo=True)
# 打开数据库的连接会话
session = sessionmaker(engine)
# 保证线程安全
db_session = scoped_session(session)
# 获取基类
Base = declarative_base()


class User(Base):
    # 表结构的反射加载
    __table__ = Table('user', Base.metadata, autoload_with=engine)


class Favorite(Base):
    # 表结构的反射加载
    __table__ = Table('favorite', Base.metadata, autoload_with=engine)


class Article(Base):
    # 表结构的反射加载
    __table__ = Table('article', Base.metadata, autoload_with=engine)


@app.route('/')
def my_favorite():
    keyword = request.args.get('keyword')
    result = db_session.query(Article).filter(
        or_(Article.title.like('%' + keyword + '%'), Article.article_content.like('%' + keyword + '%'))
    ).all()
    for r in result:
        print(r.title)

    return 'ok'


if __name__ == '__main__':
    app.run(debug=True)
